package com.cy.service;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        map.put("status", 429);
        if(e instanceof DegradeException){
            //out.println("<h2>服务暂时不可访问</h2>");
            map.put("message", "服务暂时不可访问");
        }else {
            //out.println("<h2>访问太频繁，稍等片刻在访问</h2>");
            map.put("message","访问太频繁，稍等片刻在访问");
        }
        String jsonStr=new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}
